package gpstools.util;

import gpstools.TrainingPoint;
import gpstools.track.TrackPoint;

import java.util.List;

public class TrainingPoints {

    private final List<? extends TrainingPoint> points;

    public TrainingPoints(List<? extends TrainingPoint> points) {
        this.points = points;
    }

    public TrainingPoint pointByDistance(double distance) {
        // TODO refactor
        double fromStart = 0;
        for (int i = 1; i < points.size(); i++) {
            final TrainingPoint prev = points.get(i - 1);
            final TrainingPoint curr = points.get(i);
            final double d = gpstools.Points.distance(curr,prev);
            fromStart += d;
//            System.out.println(i + ": " + fromStart);
            if (fromStart >= distance) {
                System.out.println(fromStart + ": " + distance);
                final double rev = fromStart - distance;
                final double ratio = rev / d;

                long time = Math.round(curr.getTime() - (curr.getTime() - prev.getTime()) * ratio);
                double lon = curr.getLongitude() - (curr.getLongitude() - prev.getLongitude()) * ratio;
                double lat = curr.getLatitude() - (curr.getLatitude() - prev.getLatitude()) * ratio;
                double ele = curr.getElevation() - (curr.getElevation() - prev.getElevation()) * ratio;
                Short hr = null;
                if (curr.getHeartRate() != null && prev.getHeartRate() != null) {
                    hr = (short) Math.round(curr.getHeartRate() - (curr.getHeartRate() - prev.getHeartRate()) * ratio);
                }
                Short cad = null;
                if (curr.getCadence() != null && prev.getCadence() != null) {
                    cad = (short) Math.round(curr.getCadence() - (curr.getCadence() - prev.getCadence()) * ratio);
                }
                return TrackPoint.builder(new gpstools.Point(lat, lon, ele)).time(time).heartRate(hr).cadence(cad).build();
            }
        }
        return null;
    }

}
